package cn.school.web;

import cn.school.entity.Subject;
import cn.school.service.GradeService;
import cn.school.service.SubjectService;
import cn.school.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;


@WebServlet(name = "addSubject",urlPatterns = {"/toAddSubject","/addSubject"})
public class AddSubject extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        Enumeration<String> headerNames = req.getHeaderNames();
//        while (headerNames.hasMoreElements()){
//            String h = headerNames.nextElement();
//            String v=req.getHeader(h);
//            System.out.println(h+":"+v);
//        }
//        String liulanqi=req.getHeader("user-agent");
//        //response.sendRedirect("error.jsp")
        //req.setAttribute("grades", GradeService.INST.findALL());

        req.getRequestDispatcher("/WEB-INF/jsp/addsubject.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String subname=req.getParameter("subjectname");
        int classhour= StringUtil.toInt(req.getParameter("classhour"));
        long gradeid= StringUtil.toLong(req.getParameter("gradeid"));

        Subject subject=new Subject(0,gradeid,subname,classhour);
        int r = SubjectService.INST.add(subject);
        if(r<1){
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().println("<script>alert('增加失败！');history.back();</script>");
            return;
        }
        req.getSession().setAttribute("msg","增加成功");
        resp.sendRedirect("subjectServlet");
    }
}
